package game;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Shot {
	private final int MAXDICES = 5;
	private final int SCORE_WHEN_3_DICES[] = {0, 1000, 200, 300, 400, 500, 600};
	private Random random;
	private List<Dice> diceList;	

	public Shot(Random rand) {
		random = rand;		
		diceList = new ArrayList<Dice>();
		
		for ( int i = 0; i < MAXDICES; i++)
			diceList.add(new Dice(random));
	}

	public void doShot() {
		for ( int i = 0; i < diceList.size(); i++)
		{
			diceList.get(i).rollDice();
			System.out.print(diceList.get(i).getNumber() + " ");
		}
		System.out.println();
	}

	public int getScore() {
		int acumulator = 0;
		int counter[] = new int[7];		
		
		countDices(counter);		
		acumulator = acumulateScoreWith3EqualDices(counter);
		
		acumulator += counter[1] * 100;
		deleteDices(1, MAXDICES);
		acumulator += counter[5] * 50;
		deleteDices(5, MAXDICES);
		
		return acumulator;
	}
	
	public int getAvailableDices()
	{
		return diceList.size();
	}

	private int acumulateScoreWith3EqualDices(int[] counter) {
		int acumulator = 0;
		for ( int diceValue = 1; diceValue < counter.length; diceValue++)
		{
			if ( counter[diceValue] >= 3 )
			{
				acumulator += SCORE_WHEN_3_DICES[diceValue];
				counter[diceValue] -= 3;
				deleteDices(diceValue, 3);
			}
		}
		return acumulator;
	}

	private void countDices(int[] counter) {
		for ( int c = 1; c < counter.length; c++)
			for ( int i = 0; i < diceList.size(); i++)
				if ( diceList.get(i).getNumber() == c )
					++counter[c];
	}
	
	private void deleteDices(int number, int maxDices)
	{
		int i = 0;
		int counter = 0;
		
		while ( i < diceList.size() && counter < maxDices)
		{
			if ( diceList.get(i).getNumber() == number)
			{
				diceList.remove(i);
				++counter;
				i = 0;
			}
			else
				++i;
		}
	}
}
